package com.sz.admin.datainfo.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sz.admin.datainfo.mapper.MonitorFileRecordMapper;
import com.sz.admin.datainfo.pojo.dto.MonitorFileRecordCreateDTO;
import com.sz.admin.datainfo.pojo.dto.MonitorFileRecordListDTO;
import com.sz.admin.datainfo.pojo.dto.MonitorFileRecordUpdateDTO;
import com.sz.admin.datainfo.pojo.po.MonitorFileRecord;
import com.sz.admin.datainfo.pojo.vo.MonitorFileRecordVO;
import com.sz.admin.datainfo.service.MonitorFileRecordService;
import com.sz.core.common.entity.PageResult;
import com.sz.core.common.entity.SelectIdsDTO;
import com.sz.core.common.enums.CommonResponseEnum;
import com.sz.core.util.BeanCopyUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 监控文件记录 Service实现
 * </p>
 *
 * @author sz-admin
 * @since 2025-09-16
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MonitorFileRecordServiceImpl implements MonitorFileRecordService {

    private final MonitorFileRecordMapper monitorFileRecordMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(MonitorFileRecordCreateDTO dto) {
        // 检查MD5是否已存在（如果提供了MD5）
        if (dto.getFileMd5() != null && !dto.getFileMd5().isEmpty()) {
            int md5Exists = monitorFileRecordMapper.checkMd5Exists(dto.getFileMd5(), null);
            CommonResponseEnum.EXISTS.message("文件MD5已存在").assertTrue(md5Exists > 0);
        }

        MonitorFileRecord monitorFileRecord = BeanCopyUtils.copy(dto, MonitorFileRecord.class);
        
        // 设置默认值
        monitorFileRecord.setDelFlag("F");
        monitorFileRecord.setCreateTime(LocalDateTime.now());
        
        // 如果未设置处理状态，默认为失败
        if (monitorFileRecord.getProcessStatus() == null) {
            monitorFileRecord.setProcessStatus("0");
        }
        
        // 如果未设置处理时间，使用当前时间
        if (monitorFileRecord.getProcessTime() == null) {
            monitorFileRecord.setProcessTime(LocalDateTime.now());
        }

        int result = monitorFileRecordMapper.insert(monitorFileRecord);
        CommonResponseEnum.SAVE_FAIL.assertTrue(result <= 0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(MonitorFileRecordUpdateDTO dto) {
        // 检查记录是否存在
        MonitorFileRecordVO existingRecord = monitorFileRecordMapper.selectById(dto.getId());
        CommonResponseEnum.INVALID_ID.assertNull(existingRecord);

        // 检查MD5是否已存在（排除当前记录）
        if (dto.getFileMd5() != null && !dto.getFileMd5().isEmpty()) {
            int md5Exists = monitorFileRecordMapper.checkMd5Exists(dto.getFileMd5(), dto.getId());
            CommonResponseEnum.EXISTS.message("文件MD5已存在").assertTrue(md5Exists > 0);
        }

        MonitorFileRecord monitorFileRecord = BeanCopyUtils.copy(dto, MonitorFileRecord.class);

        int result = monitorFileRecordMapper.updateById(monitorFileRecord);
        CommonResponseEnum.UPDATE_FAIL.assertTrue(result <= 0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(MonitorFileRecordUpdateDTO dto) {
        // 检查记录是否存在
        MonitorFileRecordVO existingRecord = monitorFileRecordMapper.selectById(dto.getId());
        CommonResponseEnum.INVALID_ID.assertNull(existingRecord);

        // 只更新carNumber和remark字段
        MonitorFileRecord monitorFileRecord = new MonitorFileRecord();
        monitorFileRecord.setId(dto.getId());
        monitorFileRecord.setCarNumber(dto.getCarNumber());
        monitorFileRecord.setRemark(dto.getRemark());

        int result = monitorFileRecordMapper.updateById(monitorFileRecord);
        CommonResponseEnum.UPDATE_FAIL.assertTrue(result <= 0);
    }

    @Override
    public PageResult<MonitorFileRecordVO> page(MonitorFileRecordListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getLimit());
        List<MonitorFileRecordVO> list = monitorFileRecordMapper.selectPageList(dto);
        PageInfo<MonitorFileRecordVO> pageInfo = new PageInfo<>(list);
        
        // Calculate total pages
        long totalPages = (pageInfo.getTotal() + dto.getLimit() - 1) / dto.getLimit();
        
        return new PageResult<>(
                dto.getPage(),
                dto.getLimit(), 
                totalPages,
                pageInfo.getTotal(),
                list
        );
    }

    @Override
    public List<MonitorFileRecordVO> list(MonitorFileRecordListDTO dto) {
        return monitorFileRecordMapper.selectList(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void remove(SelectIdsDTO dto) {
        CommonResponseEnum.INVALID_ID.assertTrue(dto.getIds() == null || dto.getIds().isEmpty());
        
        int result = monitorFileRecordMapper.deleteByIds((List<Long>) dto.getIds());
        CommonResponseEnum.DELETE_FAIL.assertTrue(result <= 0);
    }

    @Override
    public MonitorFileRecordVO detail(Long id) {
        CommonResponseEnum.INVALID_ID.assertNull(id);
        MonitorFileRecordVO record = monitorFileRecordMapper.selectById(id);
        CommonResponseEnum.INVALID_ID.assertNull(record);
        return record;
    }
}